package cn.ywyself;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;

import java.net.URL;

public class Application {

    private static final int PORT = 8087;

    public static void main(String[] args) throws Exception {
        if (isInJar()) {
            startInJar();
        } else {
            startInIDE();
        }
    }

    // 通过java -jar xxx.jar 启动
    private static void startInJar() throws Exception {
        System.out.println("jar ---- Running Jetty server on port :" + PORT);
        Server server = new Server(PORT);

        WebAppContext root = new WebAppContext();

        // 获取jar包里面的webapp路径
        final URL webappUrl = Application.class.getClassLoader().getResource("webapp");
        if (null == webappUrl) {
            throw new Exception("webapp path is null");
        }
        final String webappUrlStr = webappUrl.toExternalForm();
        System.out.println(webappUrlStr);

        root.setContextPath("/");
        // 关键步骤 : 设置webapp的目录路径:  jar:file:/path_to_jar!/webapp
        root.setWar(webappUrlStr);

        server.setHandler(root);
        server.start();
        server.join();
    }

    // ide 里面启动
    private static void startInIDE() throws Exception {
        System.out.println("ide -- Running Jetty server on port " + PORT);
        Server server = new Server(PORT);
        WebAppContext root = new WebAppContext();
        root.setContextPath("/");

        // 设置源码的配置文件。
        root.setDescriptor("src/main/webapp/WEB-INF/web.xml");
        root.setResourceBase("src/main/webapp/");

        server.setHandler(root);
        server.start();
        server.join();
    }

    /**
     * 是否以jar的方式启动
     */
    private static Boolean isInJar() {
        String classPath = Application.class.getProtectionDomain().getCodeSource().getLocation().toExternalForm();
        return classPath.contains(".jar");
    }
}
